<?php

class Common_task extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('basedao', 'mydb', TRUE);
    }

    /**
     * 增加任务
     * @param string $type 增加任务类型
     * @param string $uuid 来源表的id
     * @return array $result
     */
    public function addtask($type, $uuid)
    {
        if (self::_taskcheck($type, $uuid)) return;
        $query = $this->db->get_where('sys_taskcontrol', array('type' => $type));
        $controllist = $query->result_array();
        foreach ($controllist as $control) {
            $query = $this->db->get_where($control['src_table'], array($control['src_id'] => $uuid));
            $src = $query->row_array();
            $query = $this->db->query("SHOW FIELDS FROM " . $control['src_table']);
            $srcfield = $query->result_array();
            foreach ($srcfield as $fields) {
                $control['tgt_sql'] = str_replace("$" . $fields['Field'], $src[$fields['Field']], $control['tgt_sql']);
                $control['title'] = str_replace("$" . $fields['Field'], $src[$fields['Field']], $control['title']);
                $control['uri'] = str_replace("$" . $fields['Field'], $src[$fields['Field']], $control['uri']);
            }
            $query = $this->db->query($control['tgt_sql']);
            $targets = $query->result_array();
            foreach ($targets as $target) {
                $data = array();
                $data['type'] = $type;
                $data['memberid'] = $target[$control['tgt_member']];
                $data['title'] = $control['title'];
                $data['uri'] = $control['uri'];
                $data['targetid'] = $uuid;
                $data['target'] = $control['targetmodule'];
                $data = self::_taskdata($data);
                $this->db->insert('oa_task', $data);
            }
        }
    }

    /** 确认任务存在
     * @param $type
     * @param $targetid
     * @return bool
     */
    private function _taskcheck($type, $targetid)
    {
        $this->db->where('targetid', $targetid);
        $this->db->where('type', $type);
        $query = $this->db->get('oa_task');
        if ($query->num_rows() > 0) return true;
        else return false;
    }

    /** 完善任务字段
     * @param $data
     * @return mixed
     */
    private function _taskdata($data)
    {
        $no = 'TSK' . date("Ym-");
        $this->load->helper('guid_helper');
        $data['uuid'] = guid();
        $data['seqno'] = $this->dball->getNo($no, 3);
        $data['taskdate'] = date('Y-m-d G:i:s');
        $data['state'] = '0';
        $date['createdatetime'] = date('Y-m-d G:i:s');
        $data['createuser'] = $this->userid;
        return $data;
    }

}
